package com.jiai.cloud.base.tools;


import com.jiai.cloud.base.entity.RestResult;
import com.jiai.cloud.base.util.ErrorCode;
import com.jiai.cloud.base.exception.LoginException;
import com.jiai.cloud.base.exception.PermissionException;
import com.jiai.cloud.base.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class RestExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);

   
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
  
    private <T> RestResult<T> serviceExceptionHandler(ServiceException e) {
         LOGGER.error("服务器内部异常 ---[msg]:{}---[description]:{}", e.getMessage(),e.getDescription());
         return RestResultGenerator.genErrorResult(e.getCode(),e.getMessage(),e.getDescription());
       
    }
    
    @ExceptionHandler(PermissionException.class)
    @ResponseBody
    private <T> RestResult<T> permissionExceptioHandler(PermissionException e) {
         LOGGER.error("没有权限 ---[msg]:{}---[description]:{}", e.getMessage(),e.getDescription());
         return RestResultGenerator.genErrorResult(e.getCode(),e.getMessage(),e.getDescription());
       
    }
    @ExceptionHandler(LoginException.class)
    @ResponseBody
    private <T> RestResult<T> loginExceptionHandler(LoginException e) {
         LOGGER.error("登录异常---[msg]:{}---[description]:{}", e.getMessage(),e.getDescription());
         return RestResultGenerator.genErrorResult(e.getCode(),e.getMessage(),e.getDescription());
       
    }
    
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("msg", e.getMessage());
        mav.setViewName("error");
        return mav;
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private <T> RestResult<T> illegalParamsExceptionHandler(MethodArgumentNotValidException e) {
    	return RestResultGenerator.genErrorResult(ErrorCode.ILLEGAL_PARAMS);
    }

}